package com.example.stock.service;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.stock.entity.Stock;
import com.example.stock.util.DateUtil;
import com.example.stock.util.HolidayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author tanlvxu
 * @Date 2024/12/19 11:06
 * @Description TODO
 */
@Service
public class LastMaxStockService {


    Map<String, Stock> lastHighMap = new HashMap<>();

    @Autowired
    private IStockService stockService;

    private String curDate;


    public Map<String,Stock> getLastHighMap(){
        try {
            LocalDateTime calcTime = null;
            String calcDate = null;
            for (int i = 1; i < 10; i++) {
                // 获取当前时间
                LocalDateTime nowLocal =  LocalDateTime.now();
                nowLocal = nowLocal.plusDays(-i);
                // 定义日期时间格式
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                // 格式化当前时间
                String formattedNow = nowLocal.format(formatter);
                String workingDay = HolidayUtil.isWorkingDay(formattedNow);
                if("0".equals(workingDay)){
                    calcDate =  formattedNow;
                    calcTime = nowLocal;
                    break;
                }
            }
            //清除当天的缓存
            if(curDate != null && ObjectUtil.notEqual(curDate,calcDate)){
                curDate = null;
            }

            if(StringUtils.isBlank(curDate)){
                Date date = Date.from(calcTime.atZone(ZoneId.systemDefault()).toInstant());
                Date dayBegin = DateUtil.getDayBegin(date);
                Date dayEnd = DateUtil.getDayEnd(date);
                List<Stock> list1 = stockService.list(Wrappers.<Stock>lambdaQuery().eq(Stock::getCalcType, 3).ge(Stock::getCalcTime, dayBegin).le(Stock::getCalcTime, dayEnd));
                List<Stock> highArr = new ArrayList<>();
                list1.forEach(obj->{
                    if(Objects.equals(obj.getPriceNow(), obj.getHighLimit()) && obj.getChangePercent() > 8){
                        highArr.add(obj);
                    }
                });
                lastHighMap = highArr.stream().collect(Collectors.toMap(Stock::getCode, Function.identity()));
                curDate = calcDate;
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        return lastHighMap;
    }
}
